package com.dlust.myplayer

import android.net.Uri
import android.util.Log
import androidx.annotation.OptIn
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.net.toUri
import androidx.media3.common.C
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.common.util.UnstableApi
import androidx.media3.common.util.Util
import androidx.media3.datasource.DefaultHttpDataSource
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.dash.DashMediaSource
import androidx.media3.exoplayer.hls.HlsMediaSource
import androidx.media3.exoplayer.smoothstreaming.SsMediaSource
import androidx.media3.exoplayer.source.MediaSource
import androidx.media3.exoplayer.source.ProgressiveMediaSource
import androidx.media3.ui.PlayerView

@OptIn(UnstableApi::class)
@Composable
fun ExoPlayerScreen(
  videoUrl: String = MediaConfig.CURRENT_VIDEO_URL,
  modifier: Modifier = Modifier
) {
  val context = LocalContext.current
  var exoPlayer by remember { mutableStateOf<ExoPlayer?>(null) }
  var isPlaying by remember { mutableStateOf(false) }
  var isLoading by remember { mutableStateOf(true) }
  var currentUrl by remember { mutableStateOf(videoUrl) }
  
  // 监听URL变化，切换视频源
  LaunchedEffect(MediaConfig.currentVideoUrl.value) {
    val newUrl = MediaConfig.currentVideoUrl.value
    if (currentUrl != newUrl && exoPlayer != null) {
      // URL已变化，需要设置新的媒体源
      Log.d("ExoPlayerScreen", "URL变化: $currentUrl -> $newUrl")
      
      val defaultHttpDataSourceFactory = DefaultHttpDataSource.Factory()
      val uri = newUrl.toUri()
      val mediaSource = buildMediaSource(uri, defaultHttpDataSourceFactory, null)
      
      exoPlayer?.apply {
        setMediaSource(mediaSource)
        prepare()
        play()
        isLoading = true
      }
      
      currentUrl = newUrl
    }
  }

  // 初始化和清理播放器
  DisposableEffect(Unit) {
    Log.d("ExoPlayerScreen", "初始化ExoPlayer: $currentUrl")
    
    exoPlayer = ExoPlayer.Builder(context)
      .build()
      .apply {
        val defaultHttpDataSourceFactory = DefaultHttpDataSource.Factory()
        val uri = currentUrl.toUri()
        val mediaSource = buildMediaSource(uri, defaultHttpDataSourceFactory, null)
        setMediaSource(mediaSource)
        
        // 设置video缩放模式
        setVideoScalingMode(C.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING)
        
        // 设置是否循环播放
        repeatMode = Player.REPEAT_MODE_OFF
        
        // 准备并播放
        prepare()
        playWhenReady = true // 设置准备好就播放
      }

    val listener = object : Player.Listener {
      override fun onPlaybackStateChanged(state: Int) {
        when (state) {
          Player.STATE_BUFFERING -> {
            Log.d("ExoPlayerScreen", "播放状态: 缓冲中")
            isLoading = true
          }
          Player.STATE_READY -> {
            Log.d("ExoPlayerScreen", "播放状态: 就绪")
            isLoading = false
            isPlaying = exoPlayer?.isPlaying == true
          }
          Player.STATE_ENDED -> {
            Log.d("ExoPlayerScreen", "播放状态: 已结束")
            isLoading = false
          }
          Player.STATE_IDLE -> {
            Log.d("ExoPlayerScreen", "播放状态: 空闲")
          }
        }
      }
      
      override fun onIsPlayingChanged(isPlayerPlaying: Boolean) {
        Log.d("ExoPlayerScreen", "播放状态变化: isPlaying = $isPlayerPlaying")
        isPlaying = isPlayerPlaying
      }
      
      override fun onPlayerError(error: androidx.media3.common.PlaybackException) {
        Log.e("ExoPlayerScreen", "播放错误: ${error.message}")
        isLoading = false
      }
    }
    
    exoPlayer?.addListener(listener)

    onDispose {
      Log.d("ExoPlayerScreen", "释放ExoPlayer资源")
      exoPlayer?.removeListener(listener)
      exoPlayer?.release()
      exoPlayer = null
    }
  }

  Box(modifier = modifier) {
    // ExoPlayer视图
    AndroidView(
      factory = { ctx ->
        PlayerView(ctx).apply {
          player = exoPlayer
          useController = false // 隐藏默认控制栏
          
          // 确保正确的视频尺寸处理
//          resizeMode = PlayerView.RESIZE_MODE_FILL
          
          // 设置视频背景为黑色（避免透明背景导致的问题）
          setBackgroundColor(android.graphics.Color.BLACK)
          
          // 确保表面类型设置正确
          setShutterBackgroundColor(android.graphics.Color.BLACK)
          
          // 使用硬件加速
          setKeepContentOnPlayerReset(true)
        }
      },
      modifier = Modifier.fillMaxSize(),
      // 添加更新回调，确保PlayerView正确更新播放器状态
      update = { playerView ->
        playerView.player = exoPlayer
      }
    )

    // 加载指示器
    if (isLoading) {
      CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
    }

    // 播放控制按钮
    IconButton(
      onClick = {
        exoPlayer?.let {
          if (it.isPlaying) {
            it.pause()
          } else {
            it.play()
          }
        }
      },
      modifier = Modifier.align(Alignment.BottomCenter)
    ) {
      Icon(
        painter = painterResource(
          id = if (isPlaying) R.drawable.ic_pause else R.drawable.ic_play
        ),
        contentDescription = null,
        tint = Color.White
      )
    }
  }
}

@OptIn(UnstableApi::class)
fun buildMediaSource(
  uri: Uri,
  defaultHttpDataSourceFactory: DefaultHttpDataSource.Factory,
  overrideExtension: String?,
): MediaSource {
  return when (val type = Util.inferContentType(uri, overrideExtension)) {
    C.CONTENT_TYPE_DASH -> DashMediaSource.Factory(defaultHttpDataSourceFactory)
      .createMediaSource(MediaItem.fromUri(uri))

    C.CONTENT_TYPE_SS -> SsMediaSource.Factory(defaultHttpDataSourceFactory)
      .createMediaSource(MediaItem.fromUri(uri))

    C.CONTENT_TYPE_HLS -> HlsMediaSource.Factory(defaultHttpDataSourceFactory)
      .createMediaSource(MediaItem.fromUri(uri))

    C.CONTENT_TYPE_OTHER -> ProgressiveMediaSource.Factory(defaultHttpDataSourceFactory)
      .createMediaSource(MediaItem.fromUri(uri))

    else -> {
      throw IllegalStateException("Unsupported type: $type")
    }
  }
}